package com.designMode.interpreter.nonterminal;

import com.designMode.interpreter.AbstractExpression;
import com.designMode.interpreter.Context;
import com.designMode.interpreter.NonterminalExpression;

/**
 * 与运算表达式
 */
public class And extends NonterminalExpression {
    private final AbstractExpression left, right;

    public And(AbstractExpression left, AbstractExpression right) {
        this.left = left;
        this.right = right;
    }

    @Override
    public Object interpret(Context ctx) {
        Object leftObj = left.interpret(ctx);
        Object rightObj = right.interpret(ctx);
        //参数检查
        checkBoolean(leftObj, left.toString());
        checkBoolean(rightObj, right.toString());
        return (Boolean) leftObj && (Boolean) rightObj;
    }

    @Override
    public boolean equals(AbstractExpression obj) {
        if (obj != null && obj instanceof And) {
            return left.equals(((And) obj).left) &&
                    right.equals(((And) obj).right);
        }
        return false;
    }

    @Override
    public String toString() {
        return "(" + left.toString() + " AND " + right.toString() + ")";
    }
}
